<?php



/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Gmap
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
 
class Gmap_Model_Gmap extends Core_Model_Item_Abstract
{
  // Properties

  protected $_parent_type = 'user';

  protected $_searchTriggers = array('title', 'description');

  protected $_parent_is_owner = true;

  /**
   * @var Radcodes_Lib_Google_Map_Marker
   */
  protected $map_marker = null;
  
  /**
   * @var Radcodes_Lib_Google_Map_InfoWindow
   */
  protected $map_infowindow = null;
  
  /**
   * @var Radcodes_Lib_Google_Map_Coord
   */
  protected $map_coord = null;
  
  /**
   * Gets an absolute URL to the page to view this item
   *
   * @return string
   */
  public function getHref($params = array())
  {
    $slug = $this->getSlug();
    
    $params = array_merge(array(
      'route' => 'gmap_profile',
      'reset' => true,
     // 'user_id' => $this->owner_id,
      'gmap_id' => $this->gmap_id,
      'slug' => $slug,
    ), $params);
    $route = $params['route'];
    $reset = $params['reset'];
    unset($params['route']);
    unset($params['reset']);
    return Zend_Controller_Front::getInstance()->getRouter()
      ->assemble($params, $route, $reset);
  }

  /*
  public function getSlug()
  {
  	return Radcodes_Lib_Helper_Text::slugify($this->getTitle());
  }
  */
  
  public function getExcerpt($length=164, $truncate_string='...', $truncate_lastspace=false)
  {
  	$text = strip_tags($this->description);
    return Radcodes_Lib_Helper_Text::truncate($text, $length, $truncate_string, $truncate_lastspace);
  }
  
  
  public function getKeywords($separator = ' ')
  {
    $keywords = array();
    foreach( $this->tags()->getTagMaps() as $tagmap ) {
      $tag = $tagmap->getTag();
      $keywords[] = $tag->getTitle();
    }

    if( null === $separator ) {
      return $keywords;
    }

    return join($separator, $keywords);
  }

  public function setPhoto($photo)
  {
  	$viewer = Engine_Api::_()->user()->getViewer();
  	$gmapAlbum = $this->getSingletonAlbum();
  	
  	$params = array(
        'collection_id' => $gmapAlbum->getIdentity(),
        'album_id' => $gmapAlbum->getIdentity(),
        'gmap_id' => $this->getIdentity(),
        'user_id' => $viewer->getIdentity(),  	
  	);
  	
  	$photoItem = Engine_Api::_()->gmap()->createPhoto($params, $photo);
  	
    // Update row
    $this->modified_date = date('Y-m-d H:i:s');
    $this->photo_id = $photoItem->file_id;
    $this->save();

    return $this;
  	
  }
 
  public function getPhoto($photo_id)
  {
    $photoTable = Engine_Api::_()->getItemTable('gmap_photo');
    $select = $photoTable->select()
      ->where('file_id = ?', $photo_id)
      ->limit(1);

    $photo = $photoTable->fetchRow($select);
    return $photo;
  }
  
  public function getSingletonAlbum()
  {
    $table = Engine_Api::_()->getItemTable('gmap_album');
    $select = $table->select()
      ->where('gmap_id = ?', $this->getIdentity())
      ->order('album_id ASC')
      ->limit(1);

    $album = $table->fetchRow($select);

    if( null === $album )
   {
      $album = $table->createRow();
      $album->setFromArray(array(
        'title' => $this->getTitle(),
        'gmap_id' => $this->getIdentity()
      ));
      $album->save();
    }

    return $album;
  }


  public function isMappable()
  {
  	return $this->mappable ? true : false;
  }
  

  // Interfaces
  /**
   * Gets a proxy object for the comment handler
   *
   * @return Engine_ProxyObject
   **/
  public function comments()
  {
    return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('comments', 'core'));
  }

  /**
   * Gets a proxy object for the like handler
   *
   * @return Engine_ProxyObject
   **/
  public function likes()
  {
    return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('likes', 'core'));
  }

  /**
   * Gets a proxy object for the tags handler
   *
   * @return Engine_ProxyObject
   **/
  public function tags()
  {
    return new Engine_ProxyObject($this, Engine_Api::_()->getDbtable('tags', 'core'));
  }
  
  
  /**
   * 
   * @return Gmap_Model_Category
   */
  public function getCategory()
  {
  	if (!$this->category_id) return null;
  	
  	//$category = Engine_Api::_()->getItem('gmap_category', $this->category_id);
  	
  	$category = Engine_Api::_()->gmap()->getCategory($this->category_id);

    return $category;
  }
  
  /**
   * @return Radcodes_Lib_Google_Map_GeocodedAddress $geocoded_address
   */
  public function getRawGeocodedAddress()
  {
  	$google_map = new Radcodes_Lib_Google_Map();
  	$geocoded_address = $google_map->geocode($this->location);
  	
  	return $geocoded_address;
  }
  
  
  public function populateGeocodedFields()
  {
  	$geocoded_address = $this->getRawGeocodedAddress();
  	if ($geocoded_address)
  	{
  		$this->formatted_address = $geocoded_address->getFormattedAddress();
  		
      $this->street_address = $geocoded_address->getStreetAddress();      
      $this->city = $geocoded_address->getCity();
      $this->state = $geocoded_address->getProvince();
      $this->country = $geocoded_address->getCountryCode();
      $this->zip = $geocoded_address->getPostalCode();
  		
  		$this->lat = $geocoded_address->getLat();
  		$this->lng = $geocoded_address->getLng();
  		
  		$this->mappable = true;
  	}
  	else
  	{
  		$this->mappable = false;
  	}
  	
  	return $this->mappable;
  }
  
  /**
   * @return Radcodes_Lib_Google_Map_Marker
   */
  public function getMapMarker()
  {
    if ($this->map_marker === null)
    {
	    $marker_js_name = 'radcodes_map_marker_'.$this->getGuid();
	    $options = array(
	      'title' => $this->getTitle()
	    );
	      
	    $this->map_marker = new Radcodes_Lib_Google_Map_Marker($this->lat, $this->lng, $options, $marker_js_name);
	    
      if (($icon = $this->getMapMarkerImageIcon()) !== null)
      {
        $this->map_marker->setOption('icon', $icon);
      }
      if (($shadow = $this->getMapMarkerImageShadow()) !== null)
      {
        $this->map_marker->setOption('shadow', $shadow);
      }
      
	    
    }
    return $this->map_marker;
  }
  
  /**
   * @param Radcodes_Lib_Google_Map_Marker $marker
   */
  public function setMapMarker(Radcodes_Lib_Google_Map_Marker $marker)
  {
  	$this->map_marker = $marker;
  	return $this;
  }
  
  /**
   * @return Radcodes_Lib_Google_Map_InfoWindow
   */
  public function getMapInfoWindow()
  {
    if ($this->map_infowindow === null)
    {
    	$content = $this->getTitle();
      $options = array();
      $infowindow_js_name = 'radcodes_map_infowindow_'.$this->getGuid();
    
      $this->map_infowindow = new Radcodes_Lib_Google_Map_InfoWindow($content, $options, $infowindow_js_name);
    }
    return $this->map_infowindow;
  }
  
  /**
   * @param Radcodes_Lib_Google_Map_InfoWindow $infowindow
   */
  public function setMapInfoWindow(Radcodes_Lib_Google_Map_InfoWindow $infowindow)
  {
  	$this->map_infowindow = $infowindow;
  	return $this;
  }
  
  /**
   * @return Radcodes_Lib_Google_Map_Coord
   */
  public function getMapCoord()
  {
  	if (null === $this->map_coord)
  	{
  		$this->map_coord = new Radcodes_Lib_Google_Map_Coord($this->lat, $this->lng);
  	}
  	return $this->map_coord;
  }
  

  public function getMapMarkerImageIcon()
  {
  	
  	$category = $this->getCategory();
  	
  	if ($category)
  	{
  	  if ($category->icon_url)
      {
        $icon_js_name = 'radcodes_map_marker_image_icon_'.$this->getGuid();
        
        $category_id = $category->getIdentity();
        $marker_image = new Radcodes_Lib_Google_Map_MarkerImage($category->icon_url);
        return $marker_image;
      }
  	}
  	
  	return null;
  }
  
  public function getMapMarkerImageShadow()
  {
    
    $category = $this->getCategory();
    
    if ($category)
    {
      if ($category->shadow_url)
      {
        $icon_js_name = 'radcodes_map_marker_image_shadow_'.$this->getGuid();
        
        $category_id = $category->getIdentity();
        $marker_image = new Radcodes_Lib_Google_Map_MarkerImage($category->shadow_url);
        return $marker_image;
      }
    }
    
    return null;
  }
  
  protected function _delete()
  {
    if( $this->_disableHooks ) return;
      // Delete all albums
    $albumTable = Engine_Api::_()->getItemTable('gmap_album');
    $albumSelect = $albumTable->select()->where('gmap_id = ?', $this->getIdentity());
    foreach( $albumTable->fetchAll($albumSelect) as $gmapAlbum ) {
      $gmapAlbum->delete();
    }
    
      // Delete all field values
    $values = Engine_Api::_()->fields()->getFieldsValues($this);
    foreach ($values as $value)
    {
      $value->delete();
    }
    
    // Delete search row
    $search = Engine_Api::_()->fields()->getFieldsSearch($this);
    if ($search)
    {
      $search->delete();
    }
    
    
    parent::_delete();
  }
}